package com.faintlight.controller;

import com.faintlight.model.Contact;
import com.faintlight.service.CapsuleService;
import com.faintlight.service.ContactService;
import com.faintlight.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/contacts")
@Tag(name = "可联系的人", description = "可联系的人管理接口")
@RequiredArgsConstructor
public class ContactController {

    private static final Logger logger = LoggerFactory.getLogger(ContactController.class);

    private final ContactService contactService;
    private final UserService userService;
    private final CapsuleService capsuleService;

    @PostMapping
    @Operation(summary = "添加联系人")
    public ResponseEntity<Contact> saveContact(@RequestBody Contact contact, @RequestHeader("X-User-Id") Long userId) {
        contact.setUser(userService.getUserById(userId));
        Contact saved = contactService.saveContact(contact);
        return ResponseEntity.ok(saved);
    }

    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户的联系人列表")
    public ResponseEntity<List<Contact>> getUserContacts(@PathVariable Long userId) {
        List<Contact> contacts = contactService.getUserContacts(userId);
        return ResponseEntity.ok(contacts);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除联系人")
    public ResponseEntity<Map<String, String>> deleteContact(@PathVariable Long id, @RequestHeader("X-User-Id") Long userId) {
        contactService.deleteContact(id, userId);
        Map<String, String> response = new HashMap<>();
        response.put("message", "联系人删除成功");
        return ResponseEntity.ok(response);
    }

    // CapsuleController.java
    @GetMapping("/user/{userId}/count")
    @Operation(summary = "获取用户时光胶囊数量")
    public ResponseEntity<Long> getUserCapsuleCount(@PathVariable Long userId) {
        Long count = capsuleService.getUserCapsuleCount(userId);
        return ResponseEntity.ok(count);
    }
}